package com.shujia.flink.state;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.connector.base.DeliveryGuarantee;
import org.apache.flink.connector.kafka.sink.KafkaRecordSerializationSchema;
import org.apache.flink.connector.kafka.sink.KafkaSink;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Properties;

public class Demo06SinkKafkaExactlyOnce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.enableCheckpointing(20 * 1000);

        /*
         * Flink作为Kafka的消费端如何保证ExactlyOnce语义
         * 通过开启CheckPoint来将消费的偏移量和对应的计算结果一起CK到HDFS中
         * 如果遇到故障可以进行恢复
         */
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                .setTopics("words_exactly_once_01")
                .setGroupId("flink_grp_01")
                // 不管时earliest还是latest再次消费时，如果有已经提交过的消费位置，则会从上一次消费到的位置恢复消费
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .build();

        Properties prop = new Properties();
        prop.setProperty("transaction.timeout.ms", 15 * 60 * 1000 + "");

        KafkaSink<String> kafkaSink = KafkaSink
                .<String>builder()
                .setKafkaProducerConfig(prop)
                .setBootstrapServers("master:9092,node1:9092,node2:9092")
                .setRecordSerializer(
                        KafkaRecordSerializationSchema
                                .builder()
                                .setTopic("words_cnt_exactly_once_02")
                                .setValueSerializationSchema(new SimpleStringSchema())
                                .build()
                )
                // 写入Kafka的语义：AT_LEAST_ONCE、EXACTLY_ONCE
                /*
                 * 如果设置为EXACTLY_ONCE会出现如下错误：
                 * org.apache.flink.kafka.shaded.org.apache.kafka.common.KafkaException: Unexpected error in InitProducerIdResponse;
                 * The transaction timeout is larger
                 * than the maximum value allowed by the broker (as configured by transaction.max.timeout.ms).
                 * 错误的原因：Kafka的Broker所能允许的最大事务超时时间为15min，Flink的最大的事务超时时间默认为1小时
                 *
                 * 解决方法：通过Properties将transaction.timeout.ms配置设置在15min钟内
                 *
                 * 如果需要消费结果数据时，需要指定事务的隔离级别为：读已提交read_committed
                 * kafka-console-consumer.sh --bootstrap-server master:9092,node1:9092,node2:9092
                 * --topic words_cnt_exactly_once_02
                 * --from-beginning
                 * --isolation-level read_committed
                 *
                 * 最终延迟会变大（延时会加上CK的间隔时间）
                 *
                 * 追求性能：at_least_once
                 * 追求结果准确性（不重复不丢失）：EXACTLY_ONCE
                 */
                .setDeliverGuarantee(DeliveryGuarantee.EXACTLY_ONCE)
                .build();

        DataStreamSource<String> kafkaDS = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource");

        kafkaDS
                .flatMap((line, out) -> {
                    for (String word : line.split(",")) {
                        out.collect(word);
                    }
                }, Types.STRING)
                .map(word -> Tuple2.of(word, 1), Types.TUPLE(Types.STRING, Types.INT))
                .keyBy(kv -> kv.f0, Types.STRING)
                .sum(1)
                // 将结果整理成String格式再写入Kafka
                .map(t2 -> t2.f0 + "," + t2.f1, Types.STRING)
                .sinkTo(kafkaSink);

        env.execute();


    }
}
